<template>
  <div class="app-container">
    <el-form ref="truckForm" :model="truckForm" :rules="truckFormRule" label-width="120px" class="form-container">
      <el-row>
        <el-col :span="8" :offset="8">
          <el-form-item label-width="0" prop="name">
            <el-input v-model="truckForm.name" placeholder="请输入冷藏车名称"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-card>
        <el-form-item>
          <div class="el-card_tit">
            <span>基本信息</span>
          </div>
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="品牌：" prop="brand">
              <el-input v-model="truckForm.brand"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车辆编号：" prop="carCode">
              <el-tooltip class="item" effect="dark" content="车辆车牌号；如：苏D25547" placement="top-end">
              <el-input v-model="truckForm.carCode"/>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="验证编号：" prop="customerCode">
              <el-tooltip class="item" effect="dark" content="DP-客户编号（7位）-（X:保温箱,K:库房,C:冷藏车,G:冰柜,S:系统）-编号；如：DP-SYCZYY0-X-001" placement="top-end">
                <el-input v-model="truckForm.customerCode"/>
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="冷藏车长：">
            <span>
              <el-input-number v-model="truckForm.length" :precision="2" :min="0" label="长" @change="UpdateVolume"/>&nbsp;m，
            </span>
            <span>
              <span>宽：</span>
              <el-input-number v-model="truckForm.width" :precision="2" :min="0" label="宽" @change="UpdateVolume"/>&nbsp;m，
            </span>
            <span>
              <span>高：</span>
              <el-input-number v-model="truckForm.height" :precision="2" :min="0" label="高" @change="UpdateVolume"/>&nbsp;m
            </span>
          </el-form-item>

          <el-form-item label="车辆容积：">
            <el-input-number v-model="truckForm.volume" :precision="2" :min="0" label="容积"/>&nbsp;m³，
          </el-form-item>
        </el-row>

        <el-form-item>
          <div class="el-card_tit">
            <span>其他信息</span>
          </div>
        </el-form-item>

        <el-form-item label="购买日期：" prop="purchaseDate">
          <el-date-picker v-model="truckForm.purchaseDate" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="正常启用：" prop="isEnable">
              <el-radio-group v-model="truckForm.isEnable">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有保温门帘：" prop="hasCurtain">
              <el-radio-group v-model="truckForm.hasCurtain">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密封压条完好：" prop="isStripIntact">
              <el-radio-group v-model="truckForm.isStripIntact">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有内壁破损：" prop="hasInnerDamaged">
              <el-radio-group v-model="truckForm.hasInnerDamaged">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <div class="el-card_tit">
            <span>配送测温仪</span>
          </div>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌：" prop="thermometerBrand">
              <el-input v-model="truckForm.thermometerBrand"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量：">
              <el-input-number v-model="truckForm.thermometerCount" :min="0" label="数量"/>&nbsp;个
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-show="!isEdit">
          <div class="el-card_tit">
            <span>冷藏车图片</span>
          </div>
        </el-form-item>
        <el-form-item v-show="!isEdit" label="冷藏车图片：" prop="picList">
          <UploadImg
            :picList="truckForm.picList"
            :handleChange="handleChange"
            :handleSuccess="handleSuccess"
            :handleProgress="handleProgress"
            :Data="Data"
            :FileUrl="uploadFileUrl"
            ref="eluploadimg"
          ></UploadImg>
        </el-form-item>
        <el-form-item>
          <div class="el-card_tit">
            <span>备注</span>
          </div>
        </el-form-item>
        <el-input v-model="truckForm.remark" type="textarea"/>

        <div class="btnGroup">
          <el-button type="primary" @click="submitForm('truckForm')">提交</el-button>
          <el-button @click="resetForm('truckForm')">重置</el-button>
        </div>
      </el-card>
    </el-form>
  </div>
</template>
<script>
import UploadImg from "@/components/Upload/UploadImg3";
import { createTruck, getTruckData, updateTruck } from "@/api/truck";
import { mapGetters } from "vuex";
const defaultForm = {
  name: "",
  brand: "",
  carCode: "",
  customerCode: "",
  hasCurtain: 0,
  hasInnerDamaged: 0,
  height: 0,
  isEnable: 0,
  isStripIntact: 0,
  length: 0,
  model: "",
  purchaseDate: new Date(),
  remarks: "",
  thermometerBrand: "",
  thermometerCount: 0,
  volume: 0,
  width: 0,
  picList: []
};
export default {
  components: { UploadImg },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      uploadCount: 0,
      Data: {},
      uploadFileUrl: "http://gsp.coldcloud.com/truck/pic/insert",
      truckForm: {
        name: "",
        brand: "",
        carCode: "",
        customerCode: "",
        length: 0,
        width: 0,
        height: 0,
        volume: 0,
        purchaseDate: new Date(),
        isEnable: 1,
        hasCurtain: 1,
        isStripIntact: 1,
        hasInnerDamaged: 1,
        thermometerBrand: "",
        thermometerCount: 0,
        picList: [],
        remark: ""
      },
      truckFormRule: {
        name: [
          {
            type: "string",
            required: true,
            message: "请输入冷藏车名称",
            trigger: "blur"
          }
        ],
        brand: [
          {
            type: "string",
            required: true,
            message: "请输入冷藏车品牌",
            trigger: "blur"
          }
        ],
        carCode: [
          {
            type: "string",
            required: true,
            message: "请输入车辆编号",
            trigger: "blur"
          }
        ],
        customerCode: [
          {
            type: "string",
            required: true,
            message: "请输入验证编号",
            trigger: "blur"
          }
        ],
        thermometerBrand: [
          {
            type: "string",
            required: true,
            message: "请输入测温仪品牌",
            trigger: "blur"
          }
        ],
        picList: [
          {
            required: true,
            type: "array",
            message: "请上传冷藏车图片",
            trigger: "change"
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(["customerid"])
  },

  created() {
    if (this.isEdit) {
      this.getData();
    } else {
      this.truckForm = Object.assign({}, defaultForm);
    }
  },

  methods: {
    // 容积
    UpdateVolume() {
      this.truckForm.volume =
        this.truckForm.length * this.truckForm.width * this.truckForm.height;
    },

    handleProgress(event, file, fileList) {
      if (event.percent == 100) {
        this.uploadCount++;
        console.log(this.uploadCount);
      }
    },

    handleSuccess() {
      const that = this;
      setTimeout(function() {
        that.uploadCount--;
        if (that.uploadCount == 0) {
          that.$notify({
            title: "成功",
            message: "发布成功",
            type: "success",
            duration: 2000
          });
          that.truckForm = Object.assign({}, defaultForm);
          that.$router.push({ path: "/devices/carList" });
        }
      }, 500);
    },

    handleChange(file, fileList) {
      const isImage =
        file.raw.type == "image/png" ||
        file.raw.type == "image/jpg" ||
        file.raw.type == "image/jpeg";
      if (!isImage) {
        this.$message.error("上传图片只能是JPG或者png格式!");
      }
      if (isImage) {
        this.truckForm.picList = fileList;
      } else {
        fileList.pop();
      }
      return isImage;
    },

    // 获取表单信息
    getData() {
      this.listLoading = true;
      getTruckData({ truckId: this.$route.params.id })
        .then(response => {
          this.truckForm = response.data;
        })
        .catch(e => {
          console.log(e);
        });
    },

    // 提交
    submitForm(truckForm) {
      this.isEdit ? this.truckFormRule.picList = []: this.truckFormRule.picList =  [
          {
            required: true,
            type: "array",
            message: "请上传冷藏车图片",
            trigger: "change"
          }
        ];
      this.$refs[truckForm].validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              if (!this.isEdit) {
                const tempData = {
                  customerId: this.customerid
                };
                Object.assign(tempData, this.truckForm);
                createTruck(tempData).then(res => {
                  const truckId = res.data.insertId;
                  this.Data = { truckId };
                  this.$nextTick(() => {
                    this.$refs.eluploadimg.UploadSubmit();
                  });
                });
              } else {
                if (this.isEdit) {
                  const tempData = Object.assign({}, this.truckForm);
                  updateTruck(tempData).then(() => {
                    this.$notify({
                      title: "修改",
                      message: "修改成功",
                      type: "success",
                      duration: 2000
                    });
                    this.getData();
                  });
                }
              }
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消提交"
              });
            });
        }
      });
    },
    resetForm(truckForm) {
      this.$refs[truckForm].resetFields();
    }
  }
};
</script>

<style lang="scss" scoped>
.btnGroup {
  padding: 20px;
  border-top: 1px solid #ebeef5;
  text-align: center;
}
.picList {
  margin-bottom: 30px;
}
</style>
